import { HttpError, toSuccess, useEntityManager } from "@sker/core";
import { AutoUser } from "@sker/entities";
import { useData } from '@sker/runtime';
import { z } from "zod";
import { BaiYunCore } from "./core";

export default async () => {
    const input = z.object({
        token: z.string()
    })
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) throw new HttpError(`参数错误`)
        const setting = user.setting;
        if (!setting) throw new HttpError(`参数错误`)
        try {
            const baiyunSetting = setting.baiyun;
            const baiyun = new BaiYunCore(baiyunSetting.account, baiyunSetting.password)
            const res = await baiyun.apiUser()
            if (res) {
                return toSuccess(res)
            } else {
                throw new HttpError(`操作失败`)
            }
        } catch (e) {
            throw new HttpError(e.message)
        }
    });
}
